import React, { useRef, useEffect, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';

const MapContainer: React.FC<any> = ({
  onRenderingCompleted,
  options = {
    center: [114.295643, 30.561742],
    zoom: 11,
    showIndoorMap: false,
  },
  plugins = [],
  loca = false,
}) => {
  const mapRef = useRef<any>(null);
  const [map, setMap] = useState<any>(null);

  useEffect(() => {
    const initMap = async () => {
      (AMapLoader as any).reset();

      const config = {
        key: '788e08def03f95c670944fe2c78fa76f',
        version: '2.0',
        plugins,
      };

      if (loca) {
        Object.assign(config, { Loca: { version: '2.0.0' } });
      }

      const AMap = await AMapLoader.load(config);

      const map = new AMap.Map(mapRef.current, options);

      map.on('complete', () => {
        onRenderingCompleted && onRenderingCompleted(map, AMap);
      });
      setMap(map);
    };
    if(!mapRef.current) return

    initMap();

    return () => map?.destroy();
  }, []);

  return <div ref={mapRef} style={{ height: '100%', width: '100%' }}></div>;
};

export default MapContainer;
